package com.example.zhish.asynctask_demo001;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;

public class ProgressBarTest extends AppCompatActivity {

    private ProgressBar progressBar;
    private MyAsyncTask2 myAsyncTask2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rogress_bar_test);

        progressBar = (ProgressBar) findViewById(R.id.progressBar1);

        myAsyncTask2 = new MyAsyncTask2();
        myAsyncTask2.execute();

    }


    @Override
    protected void onPause() {
        super.onPause();
        //判断AsyncTask不为空而且正在运行
        if(myAsyncTask2!=null && myAsyncTask2.getStatus() == AsyncTask.Status.RUNNING){
            //cancel方法只是将对应的AsyncTask标记为cancel状态，并不是真正的取消线程执行
            myAsyncTask2.cancel(true);
        }

    }

    class MyAsyncTask2 extends AsyncTask<Void,Integer,Void>{

        @Override
        protected Void doInBackground(Void... params) {
            for(int i=0;i<=100;i++){

                if(isCancelled()){
                    break;
                }
                publishProgress(i);
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
        }
    }
}
